<template>
  <div>
    <BasicTable @register="registerTable" ref="tableRef">
    </BasicTable>
  </div>
</template>
<script lang="tsx" setup>
  import { ref, unref } from 'vue'
  import { BasicTable, useTable, FormSchema, TableActionType } from '@/components/Table';
  import { getSimpleConnectionList } from '@/api/connection';
  import { getDataList } from '@/api/datacenter';
  import { getEntityListByConnection } from '@/api/entity';
  import { type Nullable } from '@vben/types';

  const entityOptions = ref([]);
  const entityFieldsMap = ref({});
  const tableRef = ref<Nullable<TableActionType>>(null);

  const searchFormSchemas: FormSchema[] = [
    {
      field: 'connection_id',
      label: '企业',
      component: 'ApiSelect',
      componentProps: ({ formModel }) => {
        return {
          api: getSimpleConnectionList,
          params: {
            state: 'ongoing',
            type: 'org',
          },
          resultField: 'items',
          labelField: 'partner.name',
          valueField: 'id',
          immediate: true,
          onChange: (e) => {
            formModel.entity_key = undefined;
            clearTable();
            refreshEntityList(e);
          },
        }
      },
      colProps: { span: 8 },
    },
    {
      field: 'entity_key',
      label: '实体',
      component: 'Select',
      componentProps: {
        options: entityOptions,
        onChange: (e) => {
          clearTable();
          const tableAction = unref(tableRef);
          tableAction.setProps({
            api: getDataList,
            columns: entityFieldsMap.value[e],
          });
        },
      },
      colProps: { span: 8 },
    },
  ];

  const [registerTable, { reload, setTableData}] = useTable({
    api: '',
    columns: [],
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchemas,
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
  });

  const refreshEntityList = async (e) => {
    if (e !== undefined) {
      const params = {
        connection_id: e,
      }
      const items = (await getEntityListByConnection(params)).items;
      const options: any = [];
      for (const item of items) {
        options.push({
          label: item.name,
          key: item.key,
          value: item.key,
        });
        const fields: any[] = [];
        for (const field of item.fields) {
          const fieldItem = {
            title: field.label,
            dataIndex: field.field,
          }
          fields.push(fieldItem);
        }
        entityFieldsMap.value[item.key] = fields;
      }
      entityOptions.value = options;
    } else {
      entityOptions.value = [];
    }
  };

  function clearTable() {
    setTableData([]);
  }

</script>